/*
 * @Author: 江舟 jijiangzhou@recycloud.cn
 * @Date: 2024-03-20 08:59:03
 * @LastEditors: 江舟 jijiangzhou@recycloud.cn
 * @LastEditTime: 2024-08-06 13:39:08
 * @FilePath: \vite-project\src\utils\index.ts
 */

import { lazy } from 'react';
// import BaseLayout from 'layouts/BaseLayout';
import DefaultLayout from 'layouts/DefaultLayout';
import { Icon } from '@iconify/react/dist/iconify.js';
import { findLeafNodes } from 'utils/helper';
import NotFound from 'layouts/NotFound';

/**
 * 格式化菜单
 * @param menus
 * @param allComponents
 * @returns
 */
export function formatMenus(
    menus: any[],
    components: {
        [x: string]: any;
    },
) {
    const menuMap: {
        [x: string]: any;
    } = {};
    const menuPaths: string[] = [];
    const menuList: any[] = [];
    const routerList: any[] = [];
    const childrenStack: any[] = [];
    const firstPath = findLeafNodes(menus[0])?.[0]?.path;
    const subMenuPath: any[] = [];
    const actionPerms: string[] = [];

    function loop(list: any[], key?: string, parentMenu?: any, parentRouter?: any, menuKey?: string) {
        const routerChildren = [];
        const menuChildren = [];
        let menuCount = 0;
        for (let i = 0; i < list?.length; i++) {
            menuMap[list?.[i].path] = {
                ...list?.[i],
                ...(parentMenu
                    ? {
                          parentpath: parentMenu.path,
                      }
                    : {}),
            };
            // 按钮权限存储
            if (list?.[i].type === 3) {
                actionPerms.push(list?.[i].power);
            }
            if (!key) {
                if (list[i].filepath) {
                    routerList.push({
                        path: list[i].path,
                        ...(['BaseLayout'].includes(list[i].filepath)
                            ? list[i].filepath === 'BaseLayout'
                                ? {
                                      element: <DefaultLayout />,
                                  }
                                : {
                                      element: <DefaultLayout />,
                                  }
                            : {
                                  ...(components?.[`${list[i].filepath}.tsx`]
                                      ? { Component: lazy(()=> import(`${list[i].filepath}.tsx`)) }
                                      : {
                                            element: <NotFound />,
                                        }),
                              }),
                    });
                }
                if (list[i].showTag === 0 && parentMenu?.showTag !== 1) {
                    // 是菜单 & 菜单不隐藏 & 父菜单不隐藏
                    menuList.push({
                        showTag: list[i].showTag,
                        path: list[i].path,
                        label: list[i].label,
                        key: list[i].path,
                        index: i,
                        icon: <Icon width={20} icon={list[i]?.icon || 'icon-park-twotone:setting-two'} />,
                    });
                    menuPaths.push(list[i].path);
                }
            } else {
                if (list[i].filepath) {
                    routerChildren.push({
                        path: list[i].path,
                        ...(['DefaultLayout', 'BaseLayout'].includes(list[i].filepath)
                            ? list[i].filepath === 'DefaultLayout'
                                ? {
                                      element: <DefaultLayout />,
                                  }
                                : ''
                            : {
                                  ...(components?.[`${list[i].filepath}.tsx`]
                                      ? {
                                            Component: lazy(()=> import(`${list[i].filepath}.tsx`)),
                                        }
                                      : {
                                            element: <NotFound />,
                                        }),
                              }),
                    });
                }

                if (list[i].showTag === 0 && parentMenu?.showTag !== 1) {
                    menuChildren.push({
                        showTag: list[i].showTag,
                        path: list[i].path,
                        label: list[i].label,
                        key: list[i].path,
                        icon: <Icon width={20} icon={list[i]?.icon || 'icon-park-twotone:setting-two'} />,
                    });
                    menuPaths.push(list[i].path);
                }
            }
            // submenu
            if (list?.[i].type === 1) {
                subMenuPath.push(list[i].path);
            }

            if (list?.[i].children?.length) {
                childrenStack.push({
                    ...list?.[i],
                    key: key ? `${key}_${i}` : i,
                    menuKey: menuKey ? `${menuKey}_${menuCount}` : menuCount,
                });
            }
            if (list?.[i]?.showTag === 0) {
                // 是菜单
                menuCount++;
            }
        }
        if (key) {
            parentRouter.children = routerChildren;
            if (menuChildren?.length && parentMenu) {
                parentMenu.children = menuChildren;
            }
        }
    }

    loop(menus);
    while (childrenStack?.length) {
        const firstElement = childrenStack.shift();
        const keyArray: any[] = String(firstElement.key)?.split('_');
        const menuKeyArray: any[] = String(firstElement.menuKey)?.split('_');
        let parentMenu: any;
        let parentRouter: any;
        for (let i = 0; i < keyArray.length; i++) {
            if (i === 0) {
                parentRouter = routerList[keyArray[i]];
            } else {
                parentRouter = parentRouter?.children?.[keyArray[i]];
            }
        }
        for (let i = 0; i < menuKeyArray.length; i++) {
            if (i === 0) {
                parentMenu = menuList?.[menuKeyArray[i]];
            } else {
                parentMenu = parentMenu?.children?.[menuKeyArray[i]];
            }
        }
        loop(firstElement.children, String(firstElement.key), parentMenu, parentRouter, String(firstElement.menuKey));
    }
    return {
        menuMap,
        menuList,
        routerList,
        menuPaths,
        firstPath,
        subMenuPath,
        actionPerms,
    };
}
